import { requestGet } from "@/framework/util/http";
import type { NpmMirrorFileItem } from "@/pages/tools/common/npmmirror-types";
import type { ToolInstallVersionItem } from "@/pages/tools/common/types";
import semver from "semver";

export function getVersionListFromNpmMirror(): Promise<ToolInstallVersionItem[]> {
  return new Promise(async (resolve, reject) => {
    try {
      const resp = await requestGet<NpmMirrorFileItem[]>("https://registry.npmmirror.com/-/binary/git-for-windows/");
      const list = resp.data.filter(it => it.type === "dir" && it.name.indexOf("-rc") === -1 && it.name.indexOf("prerelease") === -1);
      const versions = list.map<ToolInstallVersionItem>(it => {
        const idx = it.name.indexOf(".windows");
        const version = it.name.substring(1, idx);
        const edition = it.name.substring(it.name.lastIndexOf(".") + 1, it.name.length - 1);
        return {
          id: it.id,
          name: it.name.substring(1, it.name.length - 1),
          version,
          edition,
          url: `${it.url}Git-${version}${+edition > 1 ? "." + edition : ""}-64-bit.exe`,
          modified: new Date(it.modified),
        };
      });
      try {
        versions.sort((a, b) => semver.compare(b.version, a.version));
      } catch (e: any) {
        versions.sort((a, b) => b.modified!.getTime() - a.modified!.getTime());
      }
      resolve(versions.slice(0, 50));
    } catch (e) {
      console.error("getVersionListFromNpmMirror error", e);
      resolve([]);
    }
  });
}
